package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os/exec"
)

func main() {
	http.HandleFunc("/cmd", execute)
	http.HandleFunc("/hello", hello)
	http.ListenAndServe(":8081", nil)
}

type CmdReq struct {
	Ip string
	Pwd string
	Cmd string
}
func hello(w http.ResponseWriter, r *http.Request) {
	OK(w, "", "hello")
}
func execute(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	req := &CmdReq{}
	json.Unmarshal(body, req)

	cmd := "./cmd.sh "+req.Ip+" " +req.Pwd+" "+"'"+req.Cmd+"'"
	out := exec.Command("/bin/bash", "-c",cmd )
	bytes,err := out.Output()
	if err != nil {
		fmt.Println(err)
	}
	resp := string(bytes)
	fmt.Println(resp)
	OK(w, resp, "")
}
func OK(w http.ResponseWriter, data interface{}, msg string) {
	rsp := make(map[string]interface{})
	rsp["code"] = 0
	rsp["msg"] = msg
	rsp["data"] = data
	rspbyte, _ := json.Marshal(rsp)
	w.Write(rspbyte)
	return
}
func Err(w http.ResponseWriter, msg string) {
	rsp := make(map[string]interface{})
	rsp["code"] = 1
	rsp["msg"] = msg
	rspbyte, _ := json.Marshal(rsp)
	w.Write(rspbyte)
	return
}